package com.example.config.es;

import lombok.Data;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

import java.time.Duration;

/*
MySQL       Elasticsearch       说明
表结构Schema  映射Mapping         映射是索引中的文档的约束，例如字段类型约束。类似数据库的表结构
表Table      索引Index           索引是文档的集合，类似数据库的表
行Row        文档Document        文档是一条条JSON格式的数据，类似数据库中的行
列Column     字段Field           字段是文档中的某行数据（即属性名+值），类似数据库中的列
SQL         DSL                 DSL是elasticsearch提供的JSON风格的请求语句，用来操作elasticsearch，实现CRUD
*/

@Configuration
@ConfigurationProperties(prefix = "spring.elasticsearch")
@Data
@EnableElasticsearchRepositories(basePackages = "com.example.mapper.es")
//@EnableElasticsearchRepositories(basePackages = "com.itheima.mp.mapper.es",considerNestedRepositories = true)
public class ElasticsearchConfig {
    private String uris;
    private String username;
    private String password;
    private long connectionTimeout;
    private long socketTimeout;

    @Bean
    public RestHighLevelClient elasticsearchClient() {
        ClientConfiguration configuration = ClientConfiguration.builder()
                .connectedTo(uris) // ES地址
                .withBasicAuth(username,password)
                .withConnectTimeout(Duration.ofSeconds(connectionTimeout))
                .withSocketTimeout(Duration.ofSeconds(socketTimeout))
                .build();
        return RestClients.create(configuration).rest();
    }

    // 注册自定义的ElasticsearchRestTemplate
//    @Bean
//    public ElasticsearchOperations elasticsearchOperations() {
//        // 使用自定义的Template，禁用自动创建索引
//        return new CustomElasticsearchRestTemplate(elasticsearchClient());
//    }

    // 禁用自动创建索引的全局配置（关键）
//    @Bean
//    public ElasticsearchProperties elasticsearchProperties() {
//        ElasticsearchProperties properties = new ElasticsearchProperties();
//        properties.setAutoCreateIndex(false); // 关闭自动创建索引
//        return properties;
//    }
}
